﻿using System;
using System.Collections.Generic;
using System.Linq;
using Medianamik.Core;
using Medianamik.Core.DAL.Repositories;
using Medianamik.Core.Sugar;
using Medianamik.UI.Web.ModalWindows.ContentManagement;
using StructureMap;

namespace Medianamik.UI.Web.Shop
{
    public partial class RegionAndTaxTypeSelector : TypeSelectorWindow
    {
        private readonly INodeTypeRepository _nodeTypeRepository = ObjectFactory
            .GetInstance<INodeTypeRepository>();

        protected override IList<NodeType> GetLegitimateChildTypes()
        {
            var childListTypes = _nodeTypeRepository.ChildsOf(ParentTypeId ?? TypeIds.Region, true, 1, false);

            if (ParentNode != null && ParentNode.NodeTypeID == TypeIds.Region)
            {
                childListTypes.Add(_nodeTypeRepository.ChildsOf(TypeIds.Tax, true, 1, false).First());
            }

            return childListTypes.OrderBy(t => t.LocalizedName).ToList();
        }

        private Guid? _parentTypeId;
        protected Guid? ParentTypeId
        {
            get { return _parentTypeId ?? (_parentTypeId = GetParentNodeIdFromQueryString()); }
        }

        private Guid? GetParentNodeIdFromQueryString()
        {
            StringHelper.IsGuid(Request.QueryString[DefaultParamNames.TypeID], ref _parentTypeId);
            return _parentTypeId;
        }
    }
}
